package com.example.visitmanage

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseActivity
import com.example.visitmanage.databinding.ActivityAddVisisterBinding
import com.example.visitmanage.viewmodel.VisitManagerViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = "/visitmanage/AddVisisterActivity")
class AddVisisterActivity : BaseActivity<ActivityAddVisisterBinding,VisitManagerViewModel>() {

    override fun initView() {
        // 返回按钮
        binding.back.setOnClickListener { finish() }

        // 保存按钮
        binding.btnSave.setOnClickListener {
            // 收集表单数据
            val data = mutableMapOf<String, Any?>()
            data["approved"] = false
            data["appointmentTime"] = binding.etStartTime.text.toString()
            data["attachments"] = listOf<String>()
            data["employeeId"] = 1 // 这里要传访问对象的id，不是名字！你需要从下拉选择中获取id
            data["id"] = 0
            data["idNumber"] = binding.etIdCard.text.toString()
            data["phoneNumber"] = binding.etPhone.text.toString()
            data["plateNumber"] = if (binding.switchParking.isChecked) binding.etPlate.text.toString() else ""
            data["purpose"] = binding.etPurpose.text.toString()
            data["requestParking"] = binding.switchParking.isChecked
            data["visitStatus"] = "待审核"
            data["visitorName"] = binding.etVisitorName.text.toString()

            // 附件上传等可后续补充
            vm.addVisister(data)
        }

        // 日期选择
        binding.etDate.setOnClickListener {
            val picker = android.app.DatePickerDialog(this)
            picker.setOnDateSetListener { _, year, month, day ->
                binding.etDate.setText("$year-${month+1}-$day")
            }
            picker.show()
        }

        // 开始时间选择
        binding.etStartTime.setOnClickListener {
            val picker = android.app.TimePickerDialog(this, { _, hour, minute ->
                binding.etStartTime.setText(String.format("%02d:%02d", hour, minute))
            }, 8, 0, true)
            picker.show()
        }
        // 结束时间选择
        binding.etEndTime.setOnClickListener {
            val picker = android.app.TimePickerDialog(this, { _, hour, minute ->
                binding.etEndTime.setText(String.format("%02d:%02d", hour, minute))
            }, 18, 0, true)
            picker.show()
        }

        // 车位开关控制
        binding.switchParking.setOnCheckedChangeListener { _, isChecked ->
            binding.etPlate.visibility = if (isChecked) android.view.View.VISIBLE else android.view.View.GONE
        }

        // 车牌输入自动格式化
        binding.etPlate.addTextChangedListener(object : android.text.TextWatcher {
            var isEditing = false
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: android.text.Editable?) {
                if (isEditing) return
                isEditing = true
                s?.let {
                    val formatted = it.toString().replace(" ", "").chunked(2).joinToString(" ")
                    if (formatted != it.toString()) {
                        it.replace(0, it.length, formatted)
                    }
                }
                isEditing = false
            }
        })

        // 到访目的字数统计
        binding.etPurpose.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                binding.tvPurposeCount.text = "${s?.length ?: 0}/200"
            }
            override fun afterTextChanged(s: android.text.Editable?) {}
        })

        // 附件上传区域点击
//        val uploadArea = findViewById<android.widget.FrameLayout>(R.id.upload)
//        uploadArea?.setOnClickListener {
//            // 示例：弹出文件选择器
//
//        }
        binding.upload.setOnClickListener {
//            val intent = android.content.Intent(android.content.Intent.ACTION_GET_CONTENT)
//            intent.type = "*/*"
//            startActivityForResult(intent, 1001)
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type = "*/*"
            intent.putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/*", "application/pdf"))
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
            startActivityForResult(intent, 1001)
        }
    }

    override fun initData() {
        // 监听添加成功
        vm.addvisisterSuccess.observe(this) {
           // android.widget.Toast.makeText(this, "添加成功", android.widget.Toast.LENGTH_SHORT).show()
         ToastUtils.showShort("添加成功")
            finish()
        }
        // 监听添加失败
        vm.errorMsg.observe(this) {
            ToastUtils.showShort("222222"+it.toString())
            //android.widget.Toast.makeText(this, it ?: "添加失败", android.widget.Toast.LENGTH_SHORT).show()
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            val uri = data?.data
            if (uri != null) {
                // 显示图片到ImageView
                binding.upload.setImageURI(uri)
                binding.upload.visibility = View.VISIBLE
            }
        }
    }
}
